<?php

namespace app\mini\model;

use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;
use app\admin\controller\ApiCommon;

class PersonCase extends Model
{
	use ActionRecordTrait;

    /**
     * 表名
     * @var string
     */
    protected $name = 'case';
    protected $deleteTime = 'deleted_at';
    protected $defaultSoftDelete = 0;

    /**
     * 案例列表
     * @param  array $request 请求参数
     * @return array
     * @author hz
     * @create 2021-10-26
     */
    public function getCaseList($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;
        // try {
            $ht = $request['ht'] ?? 0;
            $person_id      = $request['person_id'] ?? 0; // 员工id
            $customer_id    = $request['customer_id'] ?? 0; // 客户id
            $list_type      = $request['list_type'] ?? 0; // 列表类型
            if ($ht > 0 && !in_array($list_type,array(1,2,3))){
                $data              = [];
                $data['list']      = [];
                $data['dataCount'] = 0;
                return ['data' => $data];
            }
            // $person_id = 29;
            $where   = [];
            if($ht == 0){
                if(!$person_id)
                {
                    return ['error' => '您还未认证,请先认证'];
                }
                if(!$customer_id)
                {
                    return ['error' => '参数错误'];
                }

                $where = [
                    ['customer_id', '=', $customer_id],
                    ['nurse_id', '=', $person_id]
                ];

            }else{
                $shop_id = $request['shop_id'] ?? 0;
                /**
                 * 搜索暂未处理
                 */
                if($shop_id > 0){
                    $where = [
                        ['shop_id','=',$shop_id]
                    ];
                }

                if($list_type != '3'){ // 优案列表

                    $shopIds = $request['shopIds'] ?? [];
                    if($shopIds){
                        array_push($where,['shop_id','in',$shopIds]);
                    }

                }


                if($customer_id)
                {
                    array_push($where,['customer_id','=',$customer_id]);
                }
            }
            // 处理搜索数据集
            $position_id        = $request['position_id'] ?? 0;          // 位置id
            $customer_name      = $request['customer_name'] ?? "";         // 客户名称或者手机号
            $reason_id          = $request['reason_id'] ?? 0;            // 疤痕成因id
            $type_id            = $request['type_id'] ?? 0;              // 疤痕类型id
            $selection_results  = $request['selection_results'] ?? 0;    // 当前的类型
            $telephone_selection= $request['telephone_selection'] ?? 0;  // 电话初选
            $realname           = $request['realname'] ?? "";              // 审理人
            $tg_excellent_time  = $request['tg_excellent_time'] ?? "";     // 审核时间
            $sp_excellent_time  = $request['sp_excellent_time'] ?? "";      // 申请时间
            $sp_excellent_time_kaishi  = $request['sp_excellent_time_kaishi'] ?? "";      // 申请时间
            $sp_excellent_time_jieshu  = $request['sp_excellent_time_jieshu'] ?? "";      // 申请时间
            $case_results  = $request['case_results'] ?? "";      // 申请时间
            $sq_type = $request['sq_type'] ?? "";      // 评级类型
            $sq_num  = $request['sq_num'] ?? "";      // 申请次数
            //需要去处理关联查询的数据
            $market_id      = $request['market_id'] ?? '';            // 市场id - 关联店铺去查询
            // 处理搜索数据集
            if(is_array($position_id)){
                if(!empty($position_id)){
                    array_push($where,['position_id','in',$position_id]);
                }
            }else{
                if ($position_id > 0){
                    array_push($where,['position_id','=',$position_id]);
                }
            }

            if (!empty($customer_name)){
                $customerIds   = Db::name('customer')->where('customer_name','like','%'.$customer_name.'%')->whereOr('telephone','like','%'.$customer_name.'%')->column('id');
                if (!empty($customerIds)) {
                    // code...
                    array_push($where,['customer_id','in',$customerIds]);
                }
            }
            if(!empty($market_id))
            {
                $shopIds = Db::name('shop')->where('market_id','=',$market_id)->column('shop_id');
                if (!empty($shopIds)) {
                    // code...
                    array_push($where,['shop_id','in',$shopIds]);
                }
            }

            if(is_array($reason_id)){
                if(!empty($reason_id)){
                    array_push($where,['reason_id','in',$reason_id]);
                }
            }else{
                if ($reason_id > 0){
                    array_push($where,['reason_id','=',$reason_id]);
                }
            }

            // var_dump($type_id);exit;
            if(is_array($type_id)){
                if(!empty($type_id)){
                    array_push($where,['type_id','in',$type_id]);
                }
            }else{
                if ($type_id > 0){
                    array_push($where,['type_id','=',$type_id]);
                }
            }

            // echo "<pre>";
            // print_r($type_id);
            // echo "</pre>";

            if ($sq_type){

				array_push($where,['sq_type','=',$sq_type]);

			}

            if ($sq_num){

				array_push($where,['sq_num','=',$sq_num]);

			}
            /* if ($selection_results > 0){
                if($selection_results == 2 || $selection_results ==3){
                    array_push($where,['sq_type','=',$selection_results-1]);
                }else{
                    array_push($where,['selection_results','=',$selection_results]);
                }
            } */
            if ($selection_results > 0){

				array_push($where,['selection_results','=',$selection_results]);
			}

            if ($telephone_selection > 0){
                array_push($where,['telephone_selection','=',$telephone_selection]);
            }
            if ($case_results > 0){
                array_push($where,['case_results','=',$case_results]);
            }
            if ($realname > 0){
                $reviewerIds   = Db::name('admin_user')->where('realname','like','%'.$realname.'%')->column('id');
                if (!empty($reviewerIds)) {
                    // code...
                    array_push($where,['reviewer_id','in',$reviewerIds]);
                }
            }
             if (!empty($tg_excellent_time)){
                array_push($where,['tg_excellent_time','>=',strtotime($tg_excellent_time." 00:00:00")]);
                array_push($where,['tg_excellent_time','<=',strtotime($tg_excellent_time." 23:59:59")]);
            }
            if (!empty($sp_excellent_time)){
                array_push($where,['sp_excellent_time','>=',strtotime($sp_excellent_time." 00:00:00")]);
                array_push($where,['sp_excellent_time','<=',strtotime($sp_excellent_time." 23:59:59")]);
            }
            if (!empty($sp_excellent_time_kaishi)){
                array_push($where,['sp_excellent_time','>=',strtotime($sp_excellent_time_kaishi." 00:00:00")]);
            }
            if (!empty($sp_excellent_time_jieshu)){
                array_push($where,['sp_excellent_time','<=',strtotime($sp_excellent_time_jieshu." 23:59:59")]);
            }

            if ($list_type > 1) {
                array_push($where,['selection_results','in',[2,3]]);
                if ($list_type == 3) {
                    array_push($where,['is_collection','=',1]);
                }
            }
            $export = $request['export'] ?? 0;
            if ($export == 1){
                $ids = $request['id'] ?? [];
                array_push($where,['id','in',$ids]);

                $request['page']  = 1;
                $request['limit'] = 10000000;
            }
            $field = ['id,shop_id,customer_id,nurse_id,position_name,reason_name,type_name,create_time,selection_results,sp_excellent_time,tg_excellent_time,collection_time,reviewer_id,is_collection,collection_time,case_results,telephone_selection','num','sqr_id','sq_type','sq_num'];
            $list = Db::name('case')->field($field)->where($where)->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->order('id DESC')->select()->toArray();
            // print_r($where);exit;

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;

            $case_type = [
                '1' => '优秀案例',
                '2' => '满意案例',
            ];
            $dataCount = Db::name('case')->where($where)->count();

            if ($list)
            {
                $customerIds  = array_column($list, 'customer_id');
                $customerList = Db::name('customer')->where('id','in',$customerIds)->select()->toArray();
                $shopIds  = array_values(array_unique(array_column($list, 'shop_id')));
                $shopList = Db::name('shop')->where('shop_id','in',$shopIds)->column(['shop_name','market_name'],'shop_id');
                // print_r($shopIds);exit;
                $customerList = array_column($customerList,null,'id');
                $nurse_ids    = array_column($list, 'nurse_id');
                $nurserList   = Db::name('shop_person')->where('id','in',$nurse_ids)->select()->toArray();
                $nurserList   = array_column($nurserList,null,'id');
                // print_r($nurserList);exit;
                //审核人处理
                $reviewerIds    = array_column($list, 'reviewer_id');
                $sqrIds    = array_column($list, 'sqr_id');
                $adminuserList   = Db::name('admin_user')->where('id','in',array_merge($reviewerIds,$sqrIds))->column(['realname'],'id');
                foreach ($list as $key => $value)
                {
                    $list[$key]['customer_name'] = $customerList[$value['customer_id']]['customer_name'] ?? '';
                    $list[$key]['telephone'] = $customerList[$value['customer_id']]['telephone'] ?? '';
                    $list[$key]['sex']          = $customerList[$value['customer_id']]['sex'] ?? '';
                    $list[$key]['sex']          = $list[$key]['sex'] == 1 ? '男' : '女' ;
                    $list[$key]['sq_type']      = $list[$key]['sq_type'] > 0 ? $case_type[$list[$key]['sq_type']] : '未申请';
                    $list[$key]['nurse_name']    = $nurserList[$value['nurse_id']]['name'] ?? '';
                    $list[$key]['shop_name']    = $shopList[$value['shop_id']]['shop_name'] ?? '';
                    $list[$key]['market_name']    = $shopList[$value['shop_id']]['market_name'] ?? '';
                    $list[$key]['reviewer_name']    = $adminuserList[$value['reviewer_id']] ?? '';
                    $list[$key]['sqr_name']    = $adminuserList[$value['sqr_id']]['realname'] ?? '';
                    $list[$key]['create_time']   = $value['create_time'] ? date('Y-m-d H:i:s', $value['create_time']) : '';
                    $list[$key]['tg_excellent_time'] = $value['tg_excellent_time'] ? date('Y-m-d H:i:s', $value['tg_excellent_time']) : '';
                    $list[$key]['sp_excellent_time'] = $value['sp_excellent_time'] ? date('Y-m-d H:i:s', $value['sp_excellent_time']) : '';
                    $list[$key]['collection_time']   = $value['collection_time'] ? date('Y-m-d H:i:s', $value['collection_time']) : '';
                    $list[$key]['log_num'] = Db::name('case_log')->where('case_id','=',$value['id'])->count() ?? 0;

                    if($value['case_results'] == 1){
                        $list[$key]['case_results_name'] = '服务满意';
                    }else if($value['case_results'] == 2){
                        $list[$key]['case_results_name'] = '服务不满意';
                    }else if($value['case_results'] == 3){
                        $list[$key]['case_results_name'] = '电话未通过';
                    }else if($value['case_results'] == 4){
                        $list[$key]['case_results_name'] = '电话未接通';
                    }else{
                        $list[$key]['case_results_name'] = '未知';
                    }
                    if($value['telephone_selection'] == 1){
                        $list[$key]['telephone_selection_name'] = '通过';
                    }else if($value['telephone_selection'] == 2){
                        $list[$key]['telephone_selection_name'] = '未通过';
                    }else{
                        $list[$key]['telephone_selection_name'] = '未开始';
                    }


                    if($value['nurse_id'] == $person_id){
                        $list[$key]['isDelete'] = 75;
                    }else{
                        $list[$key]['isDelete'] = 0;
                    }

                    if($list_type == 3){
                        $list[$key]['isDelete'] = 0;
                    }
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return ['data' => $data];
        // } catch (\Exception $e) {
        //     return ['error' => $e->getMessage()];
        // }
    }

    /**
     * 案例详情
     * @param  array $request 请求参数
     * @return array
     * @author hz
     * @create 2021-10-26
     */
    public function getDetail($request)
    {
        $nowTime = time();

        $year_mon = date("Y-m",$nowTime);

        $day = '-21';

        $tagTime = strtotime($year_mon.$day);



        // try {
            $person_id = $request['person_id'] ?? 0;
            // $person_id = 29;
            $case_id = $request['case_id'] ?? 0;
            if(!isset($request['ht'])){
                if(!$person_id)
                {
                	return ['error' => '您还未认证,请先认证'];

                }
            }


            if(!$case_id)
            {
                return ['error' => '参数错误'];
            }
            $where   = [];
            $where = [
                ['id', '=', $case_id]
            ];
            // $field = ['*'];
            $caseInfo  = Db::name('case')->where($where)->find();
            if($caseInfo)
            {
                $caseInfo['create_time'] = $caseInfo['create_time'] ? date('Y-m-d H:i:s',$caseInfo['create_time']) : '';
                $caseInfo['collection_time'] = $caseInfo['collection_time'] ? date('Y-m-d H:i:s',$caseInfo['collection_time']) : '';
            }else{
                return ['error' => '数据不存在'];
            }
            $list = Db::name('case_log')->where('case_id','=',$case_id)->order('id desc')->select()->toArray();

            if ($list)
            {
                foreach($list as $key => $v){
                    $list[$key]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s',$v['create_time']) : '';

                    $list[$key]['imageList'] = $v['images'] ? explode(',',$v['images']) : [];
                    $list[$key]['imageList'] = array_filter($list[$key]['imageList']);
                }
            }
            $caseListy = $this->getCaseDetailT($caseInfo['customer_id']);
			/* echo '<pre>';
			print_r($caseListy);exit; */

            $customerInfo = Db::name('customer')->where('id','=',$caseInfo['customer_id'])->find();
            $nurse_name = Db::name('shop_person')->where('id','=',$caseInfo['nurse_id'])->value('name');
            $shopInfo = Db::name('shop')->where('shop_id','=',$caseInfo['shop_id'])->field('shop_name,market_name')->find();
            // print_r($shopInfo);exit;
            $caseInfo['customer_name'] = $customerInfo['customer_name'] ?? '';
            $caseInfo['telephone'] = $customerInfo['telephone'] ?? '';
            if($caseInfo['sq_type'] == 3){
                $caseInfo['sq_type_name'] = '未申请';
            }else{
                if($caseInfo['sq_type'] == 1){
                    $caseInfo['sq_type_name'] = '申请优秀案例';
                }else{
                   $caseInfo['sq_type_name'] = '申请满意案例';
                }
            }
            $caseInfo['sex'] = $customerInfo['sex'] ?? '';
            $caseInfo['nurse_name'] = $nurse_name ?? '';
            $caseInfo['shop_name'] = $shopInfo['shop_name'] ?? '';
            $caseInfo['market_name'] = $shopInfo['market_name'] ?? '';
            if($caseInfo['selection_results']<2||$caseInfo['selection_results']==4){
                $caseInfo['selection_results2']=2;
            }else{
                $caseInfo['selection_results2']=1;
            }
            // $caseInfo['selection_results2'] = $shopInfo['market_name'] ?? '';
            if ($caseInfo['graduation_type'] == 1){
                $caseInfo['graduation_type_name'] = '已毕业';
            }else{
                if ($caseInfo['graduation_type'] == 2){
                    $caseInfo['graduation_type_name'] = '治疗中断';
                }else{
                    $caseInfo['graduation_type_name'] = '修护中';
                }
            }
            $fuwupingbi = [1=>'服务满意',2=>'服务不满意',3=>'电话不通过',4=>'电话未接通'];
            $xiaoguopingbi = [1=>'效果不满意',2=>'效果一般满意',3=>'效果满意',4=>'电话未接通'];
            $telephone_selection = [0=>'未开始',1=>'通过',2=>'未通过'];
            $selection_results2 = [1=>'未通过',2=>'通过'];
            $caseInfo['effect_results_name'] = $xiaoguopingbi[$caseInfo['effect_results']] ?? '';
            $caseInfo['case_results_name'] = $fuwupingbi[$caseInfo['case_results']] ?? '';
            $caseInfo['telephone_selection_name'] = $telephone_selection[$caseInfo['telephone_selection']] ?? '';
            $caseInfo['selection_results2_name'] = $selection_results2[$caseInfo['selection_results2']] ?? '';
            $caseInfo['tg_excellent_time'] = $caseInfo['tg_excellent_time'] ? date('Y-m-d H:i:s', $caseInfo['tg_excellent_time']) : '';
            $caseInfo['sp_excellent_time'] = $caseInfo['sp_excellent_time'] ? date('Y-m-d H:i:s', $caseInfo['sp_excellent_time']) : '';
			$caseInfo['shenqingnum'] = $caseListy['num'];
			$caseInfo['telephone'] = $caseListy['telephone'];
			$caseInfo['shenqing_time'] = $caseListy['shenqingtime'];
			$caseInfo['shenqing_position'] = $caseListy['buwei'];
			$caseInfo['shenqing_type'] = $caseListy['chengyin'];
			$caseInfo['shenqing_reason'] = $caseListy['leixing'];

            if($nowTime<$tagTime){
                $caseInfo['sq_ok'] = "1";
            }else{
                $caseInfo['sq_ok'] = "";
            }

            $caseInfo['sq_ok'] = "1";

            // print_r($caseInfo);exit;
            // $caseInfo['collection_time']   = $caseInfo['collection_time'] ? date('Y-m-d H:i:s', $caseInfo['collection_time']) : '';
            $caseInfo['list'] = $list;
            return ['data' => $caseInfo];
        // } catch (\Exception $e) {
        //     return ['error' => $e->getMessage()];
        // }
    }

	public function getCaseDetailT($id){

		//var_dump($id);

		//$id = 353392;

		$caseListInfo = Db::name('case')->where('customer_id','=',$id)->order('id DESC')->column('id,position_id,position_name,reason_name,type_name,sp_excellent_time');

		$customerInfo = Db::name('customer')->where('id','=',$id)->column('telephone');


		$date['telephone'] = $customerInfo[0]; //总共申请次数
		$date['num'] = count($caseListInfo); //总共申请次数
		$date['shenqingtime'] =$caseListInfo[0]['sp_excellent_time'] ? date('Y-m-d H:i:s', $caseListInfo[0]['sp_excellent_time']) : ''; //最后一次申请疤痕类型
		$date['buwei'] = $caseListInfo[0]['position_name']; //最后一次申请部位
		$date['chengyin'] = $caseListInfo[0]['reason_name']; //最后一次申请 疤痕成因
		$date['leixing'] = $caseListInfo[0]['type_name']; //最后一次申请疤痕类型

		/* echo '<pre>';
		print_r($customerInfo); */


		return $date;
	}


    /**
     * 获取案例跟进列表
     * @param  array $request 请求参数
     * @return array
     * @author hz
     * @create 2021-10-19
     */
    public function getLogList($request)
    {
        try {
            $person_id = $request['person_id'] ?? 0;
            // $person_id = 29;
            $case_id = $request['case_id'] ?? 0;
            if(!$person_id)
            {
                return ['error' => '您还未认证,请先认证'];
            }

            if(!$case_id)
            {
                return ['error' => '参数错误'];
            }

            $where   = [];
            $where = [
                ['case_id', '=', $case_id]
            ];

            $list = Db::name('case_log')->where($where)->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->order('id DESC')->select()->toArray();

            $dataCount = Db::name('case_log')->where($where)->count();

            if ($list)
            {
                foreach($list as &$v){
                    $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s',$v['create_time']) : '';
                    $v['imageList'] = $v['images'] ? explode(',',$v['images']) : [];
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return ['data' => $data];
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    /**
    * 添加跟进
    */
    public function addCaseLog($request)
    {
        try {
            $person_id = $request['person_id'] ?? 0;
            // $person_id = 29;
            $case_id = $request['case_id'] ?? 0;
            if(!isset($request['ht'])){
                if(!$person_id)
                {
                    return ['error' => '您还未认证,请先认证'];
                }
                $user_id = $request['person_id'];
            }else{
                $user_id = $request['user_id'] ?? 0;
            }


            if(!$case_id)
            {
                return ['error' => '参数错误'];
            }
            if(! $request['content'])
            {
                return ['error' => '请填写跟进内容'];
            }
            if (is_array($request['iamges'])){
                $images = implode(',',$request['iamges']);
            }else{
                $images = $request['iamges'];
            }
            $param['case_id'] = $case_id;
            $param['content'] = $request['content'];
            $param['images'] = $images;
            $param['create_time']     = time();
            // print_r($param);exit();
            $res = Db::name('case_log')->insertGetId($param);
            if($res)
            {
                return ['error' => '创建成功', 'data' => ['id'=>$res]];
            }
            else{
                throw new \Exception('创建失败');
            }

        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    public function addCase($request)
    {
        try {
            //客户id
            $customer_id = $request['customer_id'] ?? 0;
            //店铺id
            $shop_id = $request['shop_id'] ?? 0;
            //位置id
            $position_id = $request['position_id'] ?? 0;
            //成因id
            $reason_id = $request['reason_id'] ?? 0;
            //类型id
            $type_id = $request['type_id'] ?? 0;

            $graduation_type = $request['graduation_type'] ?? 3;

            if(!$customer_id)
            {
                return ['error' => '请选择创建案例的客户'];
            }
            if(!$shop_id)
            {
                return ['error' => '请选择创建案例的店铺'];
            }
            if(!$position_id)
            {
                return ['error' => '请选择创建案例的位置'];
            }
            if(!$reason_id)
            {
                return ['error' => '请选择创建案例的疤痕成因'];
            }
            if(!$type_id)
            {
                return ['error' => '请选择创建案例的疤痕类型'];
            }
            $setting = array($position_id,$reason_id,$type_id);
            $sD = Db::name('setting')->where('id','in',$setting)->column('name','id');
            $nurse_id = Db::name('customer')->where('id','=',$customer_id)->value('nurse_id') ?? 0;
            // if(count($sD) != 3){
            //     return ['error' => '参数类型错误'];
            // }
            if($nurse_id == 0){
                return ['error' => '当前用户没有护理师，请为该用户选择护理师'];
            }
            $addData['shop_id'] = $shop_id;
            $addData['customer_id'] = $customer_id;
            $addData['position_id'] = $position_id;
            $addData['position_name'] = $sD[$position_id];
            $addData['reason_id'] = $reason_id;
            $addData['reason_name'] = $sD[$reason_id];
            $addData['type_id'] = $type_id;
            $addData['nurse_id'] = $nurse_id;
            $addData['type_name'] = $sD[$type_id];
            $addData['create_time'] = time();
            $addData['graduation_type'] = $graduation_type;
            // print_r();exit;
            $addData['num'] = $this->getNum();
            $res = Db::name('case')->insertGetId($addData);
            $saveCustomer = [];
            $saveCustomer['final_case'] = time();
            if($graduation_type == 1){
                $saveCustomer['graduation'] = 1;
                $saveCustomer['graduation_time'] = time();
            }
            Db::name('customer')->where('id','=',$customer_id)->update($saveCustomer);
            if($res)
            {
                return ['error' => '创建成功', 'data' => ['id'=>$res]];
            }
            else{
                throw new \Exception('创建失败');
            }
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

     public function saveCase($request)
    {
        try {
            //案例id
            $case_id = $request['case_id'] ?? 0;
            //位置id
            $position_id = $request['position_id'] ?? 0;
            //成因id
            $reason_id = $request['reason_id'] ?? 0;
            //类型id
            $type_id = $request['type_id'] ?? 0;

            if(!$case_id)
            {
                return ['error' => '请选择创建案例的客户'];
            }
            if(!$position_id)
            {
                return ['error' => '请选择创建案例的位置'];
            }
            if(!$reason_id)
            {
                return ['error' => '请选择创建案例的疤痕成因'];
            }
            if(!$type_id)
            {
                return ['error' => '请选择创建案例的疤痕类型'];
            }
            $saveData['position_id'] = $position_id;
            $saveData['reason_id'] = $reason_id;
            $saveData['type_id'] = $type_id;
            $res = Db::name('case')->where('id','=',$case_id)->update($saveData);

            if($res)
            {
                return ['error' => '编辑成功', 'data' => ['id'=>$res]];
            }
            else{
                throw new \Exception('创建失败');
            }
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    public function getNum()
    {
        $num = date('YmdHis').rand(10000,99999);
        // print_r($num);exit;
        $res = Db::name('case')->where('num','=',$num)->column('id');
        if ($res) {
            return $this->getNum();
        }else{
            return $num;
        }
    }

    public function setTj($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        // $res = Db::name('case')->where('id','=',$request['user_id'])->select()->toArray();
        $res = Db::name('case')->where('id','=',$request['case_id'])->find();

        // echo "<pre>";
        // print_r($res);
        // echo "</pre>";
        // exit;
        if(!$res){
            return ['error' => '数据不存在'];
        }else{
            if($res['sq_num']<3){

                $sq_num = bcadd($res['sq_num'],1,0);

                $case_id = $request['case_id'] ?? 0;
                $saveData['sqr_id']             = $request['user_id'] ?? 0;
                $saveData['sp_excellent_time']  = time();
                $saveData['selection_results']  = 1;
                $saveData['telephone_selection']  = 0;
                $saveData['telephone_time']  = 0;
                $saveData['selection_results']  = 1;
                $saveData['tg_excellent_time']  = 0;
                $saveData['sq_type']  = $request['type'] ?? 0;
                $saveData['sq_num']   = $sq_num;

                // echo "<pre>";
                // print_r($saveData);
                // echo "</pre>";
                // exit;

                // $res = Db::name('case')->where('id','=',$case_id)->find();
                if($res['sqr_id'] > 0){
                    if ($res['telephone_selection'] != 2){
                        if ($res['selection_results'] != 4){
                            // return ['error' => '申请已提交，请勿重复申请'];
                        }
                    }
                }

                $bool = Db::name('case')->where('id','=',$case_id)->update($saveData);

                if($bool)
                {
                    $add_log = [
                        'case_id' => $case_id,
                        'staff_id' => $request['user_id'] ?? 0,
                        'shop_id' => $res['shop_id'],
                        'case_type' => $request['type'] ?? 0,
                        'create_time' => time(),
                    ];

                    $id = Db::name('applycase_log')->insertGetId($add_log);

                    return ['error' => '申请成功', 'data' => []];
                }
                else{
                    throw new \Exception('申请失败');
                }

            }else{
                throw new \Exception('该案例已不可提交');
            }
        }



    }

    public function psCase($setData)
    {
        // echo "<pre>";
        // print_r($setData);
        // echo "</pre>";
        // exit;

        $case_id = $setData['case_id'] ?? 0;

        $res = Db::name('case')->where('id','=',$case_id)->find();

        $sq_type = $res['sq_type'];

        if($sq_type == 1){ // 优秀案例

            if($setData['telephone_selection'] == 2){ // 电话评选未通过

                if($res['sq_num']<3){
                    // 调用案例初始化接口

                    $res = $this->reductionCase($case_id);

                    if($res){
                        return ['error' => '电话评级未通过，已初始化案例状态', 'data' => []];
                    }else{
                        return ['error' => '提交失败', 'data' => []];
                    }

                    // var_dump($res);

                    // echo "调用案例初始化接口";
                    exit;
                }

            }

        }

        if($sq_type == 1){ // 满意案例

        }

        $saveData['case_results']  = $setData['case_results'] ?? 0;
        $saveData['effect_results']     = $setData['effect_results'] ?? 0;
        $saveData['telephone_selection']       = $setData['telephone_selection'] ?? 0;
        $saveData['return_visit_record']= $setData['return_visit_record'] ?? '';
        $saveData['telephone_time']= time();
        $saveData['telephone_user_id']= $setData['user_id'] ?? 0;

        // echo "<pre>";
        // print_r($saveData);
        // echo "</pre>";
        // exit;

        if(!$case_id)
        {
            // return ['error' => '请选择评级的服务'];
        }
        if(!in_array($saveData['case_results'],[1,2,3]))
        {
            // return ['error' => '请选择服务评级'];
        }
        if(!in_array($saveData['effect_results'],[1,2,3]))
        {
            // return ['error' => '请选择效果评比'];
        }
        if(!in_array($saveData['telephone_selection'],[1,2]))
        {
            // return ['error' => '请选择最终结果'];
        }
        if($saveData['telephone_selection'] == 2){
            $saveData['telephone_selection'] = 0;
        }
        if(empty($saveData['return_visit_record']))
        {
            // return ['error' => '回访记录不能为空'];
        }
        $res = Db::name('case')->where('id','=',$case_id)->find();
        if(!$res)
        {
            return ['error' => '评选的案例不存在'];
        }
        if($res['sp_excellent_time'] == 0)
        {
            return ['error' => '该案例暂未申请评选'];
        }
        if($res['telephone_selection'] > 0)
        {
            return ['error' => '该评选已被处理'];
        }
        $res = Db::name('case')->where('id','=',$case_id)->update($saveData);
        if($res)
        {
            return ['error' => '电话评级成功', 'data' => []];
        }
        else{
            throw new \Exception('创建失败');
        }
    }

    public function jspsCase($setData)
    {
        // echo "<pre>";
        // print_r($setData);
        // echo "<pre>";
        // exit;

        $case_id                        = $setData['case_id'] ?? 0;
        $res = Db::name('case')->where('id','=',$case_id)->find();

        if(!$res)
        {
            return ['error' => '评选的案例不存在'];
        }
        // 技术评审内容
        $selection_results              = $setData['selection_results2'] ?? 2; //最终评审状态

        // 判断技术评级的结果
        if($selection_results == 2 && $res['sq_num']<3){

            // 调用案例初始化接口
            $res = $this->reductionCase($case_id);

            if($res){
                return ['error' => '技术评级未通过，已初始化案例状态', 'data' => []];
            }else{
                return ['error' => '提交失败', 'data' => []];
            }

        }

        if(!in_array($selection_results,[1,2]))
        {
            return ['error' => '请选择技术评审结果'];
        }
        if ($selection_results == 1){
            $saveData['selection_results']  = $res['sq_type']==1?2:3;
        }else{
            $saveData['selection_results']  = 4;
        }
        $saveData['two_content']        = $setData['two_content'] ?? 0; //技术评审内容
        $saveData['tg_excellent_time']  = time();   // 通过审核时间
        $saveData['reviewer_id']        = $setData['user_id'] ?? 0; // 操作人id
        // 添加案例时的资料
        $position_id    = $setData['position_id'] ?? 0; // 评选位置-新增
        $reason_id      = $setData['reason_id'] ?? 0; // 形成原因-新增
        $type_id        = $setData['type_id'] ?? 0; // 疤痕类型-新增
        $settingList = Db::name('setting')->where('id','in',[$position_id,$reason_id,$type_id])->column('name','id');
        // print_r($settingList);exit;
        if(!$settingList[$position_id]){
            return ['error' => '评选位置不存在'];
        }
        $saveData['position_id']   = $position_id; //评选位置
        $saveData['position_name'] = $settingList[$position_id]; //形成原因
        if(!$settingList[$reason_id]){
            return ['error' => '形成原因不存在'];
        }
        $saveData['reason_id']   = $reason_id; //评选位置
        $saveData['reason_name'] = $settingList[$reason_id]; //形成原因
        if(!$settingList[$type_id]){
            return ['error' => '疤痕类型不存在'];
        }
        $saveData['type_id']        = $type_id; //评选位置
        $saveData['type_name']      = $settingList[$type_id]; //形成原因
        if(!$case_id)
        {
            return ['error' => '请选择评级的服务'];
        }
        if(empty($saveData['two_content']))
        {
            // return ['error' => '评选结果内容不能为空'];
        }
        if($res['sp_excellent_time'] == 0)
        {
            return ['error' => '该案例暂未申请评选'];
        }
        if($res['telephone_selection'] == 0)
        {
            return ['error' => '该案例电话评选暂未处理'];
        }
        // 电话评选内容的修改
        $saveData['case_results']   = $setData['case_results'] ?? 0; //服务评级1满意2不满意3通过'
        $saveData['effect_results'] = $setData['effect_results'] ?? 0; //效果评级，1效果不满意，2一般3满意4不通过
        $saveData['telephone_selection'] = $setData['telephone_selection'] ?? 0; //电话评选0未开始1通过2未通过
        $saveData['return_visit_record'] = $setData['return_visit_record'] ?? ''; //电话回访记录
        if($setData['case_results'] == 0){
            return ['error' => '请选择服务评级'];
        }
        if($setData['effect_results'] == 0){
            return ['error' => '请选择效果评级'];
        }
        if($setData['telephone_selection'] == 0){
            return ['error' => '请选择电话评级结果'];
        }
        if(empty($setData['return_visit_record'])){
            // return ['error' => '请填写电话回访内容'];
        }
        $saveData['is_collection']   = $setData['is_collection'] ?? 0;
        $saveData['collection_time'] = $saveData['is_collection'] == 1?time():0;
        // print_r($saveData);exit;
        $res = Db::name('case')->where('id','=',$case_id)->update($saveData);
        if($res)
        {
            return ['error' => '技术评级成功', 'data' => []];
        }
        else{
            throw new \Exception('创建失败');
        }
    }

     public function addpsCase($setData)
    {
        $case_id                        = $setData['case_id'] ?? 0;
        $saveData['is_collection']      = 1;
        $saveData['collection_time']    = time();
        if(!$case_id)
        {
            return ['error' => '请选择入库的案例'];
        }

        $res = Db::name('case')->where('id','=',$case_id)->update($saveData);
        if($res)
        {
            return ['error' => '已加入案例库', 'data' => []];
        }
        else{
            throw new \Exception('创建失败');
        }
    }

    public function delCase($setData)
    {
        // echo "<pre>";
        // print_r($setData);
        // echo "</pre>";
        // exit;
        try {
            $case_id = $setData['case_id'];
            $res = Db::name('case')->where('id','=',$case_id)->find();
            if($res){
                $customer_id = $res['customer_id'];
                $saveCustomer = [];
                $where = [];
                array_push($where,['customer_id','=',$customer_id]);
                array_push($where,['graduation_type','=',1]);
                $count = Db::name('case')->where('id','=',$case_id)->count();
                $count = bcsub($count,1);
                if($res['graduation_type'] == 1 && $count){
                    $saveCustomer['graduation'] = 0;
                    $saveCustomer['graduation_time'] = 0;
                    Db::name('customer')->where('id','=',$customer_id)->update($saveCustomer);
                }
                Db::name('case')->where('id','=',$case_id)->delete();
                Db::name('case_log')->where('case_id','=',$case_id)->delete();
            }
            return ['error' => '删除成功', 'data' => []];
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }


    // 初始化案例状态
    public function reductionCase($case_id)
    {
        $case = Db::name('case')->where('id','=',$case_id)->find();

        // echo "<pre>";
        // print_r($case);
        // echo "</pre>";
        // exit;

        if($case['sq_num']<3){

            $reductionData = [
                'is_excellent'        => '0', // 是否优案
                'is_collection'       => '0', // 是否入案例库
                'collection_time'     => '0', // 入库时间
                'sp_excellent_time'   => '0', // 申请优案时间
                'tg_excellent_time'   => '0', // 通过优案时间
                'effect_results'      => '0', //
                'case_results'        => '0', //
                'reviewer_id'         => '0', //
                'two_content'         => '',  //
                'telephone_selection' => '0', //
                'telephone_time'      => '0', //
                'telephone_user_id'   => '0', //
                'selection_results'   => '0', //
                'sqr_id'              => '0', //
                'sq_type'             => '0', //
            ];

            $bool = Db::name('case')->where('id','=',$case_id)->update($reductionData);

            return $bool;

        }else{

            return [
                'code'  => '301',
                'error' => '已满3次',
            ];

        }
    }

    // 查询顾客已评选的案例记录
    public function caseHistoryLog($request)
    {

        $case_id = $request['case_id'];

        $where = [];

        array_push($where,['id','=',$case_id]);

        $customer_id = Db::name('case')->where($where)->value('customer_id');

        $where = [];

        array_push($where,['id','<>',$case_id]);

        array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['selection_results','in',[2,3]]);

        $case_list = Db::name('case')->where($where)->select()->toArray();

        // echo "<pre>";
        // print_r($case_list);
        // echo "</pre>";

        $case_type = [
            '1' => '优秀案例',
            '2' => '满意案例',
        ];

        $shop_ids = array_values(array_unique(array_column($case_list,'shop_id')));

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shopList = Db::name('shop')->where($where)->column('shop_name','shop_id');


        $nurse_id = array_values(array_unique(array_column($case_list,'nurse_id')));

        $where = [];

        array_push($where,['id','in',$nurse_id]);

        $nurseList = Db::name('shop_person')->where($where)->column('name','id');


        $list = [];
        foreach ($case_list as $key => $value) {

            $one = [];

            $one['id'] = $value['id'];

            $one['sp_excellent_time'] = date('Y-m-d H:i:s',$value['sp_excellent_time']);

            $one['tg_excellent_time'] = date('Y-m-d H:i:s',$value['tg_excellent_time']);

            $one['selection_results'] = $value['selection_results'];

            $one['shop_name'] = $shopList[$value['shop_id']] ?? '';

            $one['nurse_name'] = $nurseList[$value['nurse_id']] ?? '';

            $one['position_name'] = $value['position_name'];

            $one['reason_name'] = $value['reason_name'];

            $one['type_name'] = $value['type_name'];

            $one['reviewer_name'] = $value['reviewer_id'];

            array_push($list,$one);

        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        return [
            'data' => $list,
        ];
    }
}
